const User = require('../models/admin_users');
const authCodeFunc = require('../utils/authCode');

module.exports = {
    /* 设置头部信息 */
    allowAll: function (req, res, next) {
        res.header("Access-Control-Allow-Headers", "*");
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
        res.header('Access-Control-Allow-Credentials', true);

        next()
    },

    /* 用户鉴权 */
    allowUser: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                let password = user_info[2];

                const users = await User.select({ id: user_info[0] });
                const user = users[0];
                let user_password = authCodeFunc(user.user_password, 'DECODE');

                if (!user && password != user_password.srt) return res.json({ code: 0, msg: "你无权操作" });

                next()

            } else {
                res.json({ code: 0, data: "请登录后操作" })
            }

        } catch (e) {
            res.json({ code: 0, data: e })
        }
    }
}